package com.intramirror.product.algorithm.impl;

import com.intramirror.product.algorithm.IAggregateAlgorithm;
import com.intramirror.product.entity.AggregateRuleType;
import com.intramirror.product.entity.PatternFromTwo;
import com.intramirror.product.entity.Product;
import com.intramirror.product.entity.Spu;
import com.intramirror.product.exception.BusinessException;
import com.intramirror.product.mapper.AggregateMapper;
import com.intramirror.utils.transform.JsonTransformUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created on 2018/1/30.
 * @author 123
 */
@Service("matchFromTwo")
public class MatchFromTwo extends BaseAggregateAlgorithm implements IAggregateAlgorithm {
    private static final Logger LOGGER = LoggerFactory.getLogger(MatchFromTwo.class);

    @Autowired
    AggregateMapper aggregateMapper;

    @Override
    public Spu aggregateWithPattern(Product product, String pattern) throws BusinessException {
        PatternFromTwo patternFromTwo = JsonTransformUtil.readValue(pattern, PatternFromTwo.class);

        LOGGER.debug("Get rule with type {}, {} designer pattern {}, color code pattern {}.", AggregateRuleType.MATCH_FROM_TWO, pattern,
                patternFromTwo.getDesigner_id(), patternFromTwo.getColor_code());

        String designerIdSrc = product.getDesignerId();
        String colorCodeSrc = product.getColorCode();

        if (patternFromTwo.getRtrim_color_code() != null && patternFromTwo.getRtrim_color_code()) {
            int index = designerIdSrc.lastIndexOf(product.getColorCode());
            if (index + colorCodeSrc.length() == designerIdSrc.length()) {
                designerIdSrc = designerIdSrc.substring(0, index);
            } else {
                LOGGER.info("Not find color code in designerId.");
            }
        }

        if (patternFromTwo.getPre_designer_id_replace() != null) {
            designerIdSrc = this.replaceWithPattern(designerIdSrc, patternFromTwo.getPre_designer_id_replace(), patternFromTwo.getPre_designer_id_replace_to());
        }

        if (patternFromTwo.getPre_color_code_replace() != null) {
            colorCodeSrc = this.replaceWithPattern(colorCodeSrc, patternFromTwo.getPre_color_code_replace(), patternFromTwo.getPre_color_code_replace_to());
        }

        product.setDesignerId(designerIdSrc);
        product.setColorCode(colorCodeSrc);
        Spu matchedSpu = exactMatchWithExistsSpu(product);
        if (matchedSpu != null) {
            return matchedSpu;
        }

        inexactMatchWithExistsSpu(product);

        Spu spu = new Spu();
        String designerId = parseSingleField(designerIdSrc, patternFromTwo.getDesigner_id());
        String colorCode = parseSingleField(colorCodeSrc, patternFromTwo.getColor_code());

        spu.setDesignerId(designerId);
        spu.setColorCode(colorCode);
        return spu;
    }

    private String parseSingleField(String srcField, String pattern) throws BusinessException {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(srcField);

        try {
            if (m.find()) {
                return m.group(1);
            } else {
                LOGGER.debug("Could not match designerId and colorCode.");
                throw new BusinessException("Could not match field " + srcField + " with pattern " + pattern);
            }
        } catch (Exception e) {
            throw new BusinessException("Get designerId and colorCode failed.", e);
        }

    }
}
